package service;
import java.util.List;

import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Record;

import model.DaliyItems;
import model.Station;

public class DaliyItemsService extends BaseService {

	public List<DaliyItems> getList() {
		return DaliyItems.dao.findOrderBy( "id,orderNum,type,duration,title,content" , "type,orderNum ASC");
	}

	public Ret save(DaliyItems daliyItems) {
		daliyItems.setMaxOrderNum() ;	
	    Long id = daliyItems.getId();
	    if(null == id){
	        daliyItems.save();
	    }else{
	        daliyItems.update() ;
	    }
	    return ok() ;
	}

	public Ret delete(Long id) {
        DaliyItems daliyItems = DaliyItems.dao.findById(id);
        if(null == daliyItems){
            return fail();
        }
        return daliyItems.delete() ? ok() : fail() ;
    }
	
	public boolean hasRecord(List<Record> records , Long daliyItemsId) {
		for (Record daliyRecord : records) {
			if (daliyRecord.getLong("daliyItemsId").equals(daliyItemsId) && daliyRecord.getInt("duration") == 7 ) {
				return true ;
			}
		}
		return false ;
	}

	public Ret list(Station station) {
		
		return Ret.create("msg" , "empty -- test") ;
		
//		int type = station.getType() ;
//		Long stationId = station.getId() ;
//		List<Record> list = DaliyItems.dao.findTitleByType(type);
//		DaliyRecords daliyRecords = DaliyRecords.dao.findFirstByStationId(stationId);
//		List<Record> records = DaliyRecord.dao.findRecords(daliyRecords);
//		for (Record record : list) {
//			String title = record.getStr("title");
//			List<Record> daliyItems = DaliyItems.dao.findByTitleAndType( type , title );
//			for (Record items : daliyItems) {
//				Long daliyItemsId = items.getLong("id");
//				boolean hasRecords = this.hasRecord(records, daliyItemsId);
//				DaliyRecord daliyRecord = DaliyRecord.dao.findFirstByStationIdAndDaliyItemsId(stationId, daliyItemsId);
//				if (null == daliyRecord) {
//					items.set("lastTime", "");
//					items.set("dued", true);
//					items.set("isNormal", true);
//					items.set("hasRecords", hasRecords);
//					continue ;
//				}
//				int days = items.getInt("duration");
//				if (days == 180 && !station.getAutoCalibrate() && station.isGasType() ) {
//					days = 90 ;
//				}
//				Date nextTime = DateKits.addDay(daliyRecord.getCreateTime() , days);
//				items.set("days", DateKits.getDays(daliyRecord.getCreateTime()));
//				items.set("lastTime", DateKits.toStr(daliyRecord.getCreateTime()));
//				items.set("dued", nextTime.getTime() < System.currentTimeMillis() );
//				items.set("isNormal", daliyRecord.getIsNormal());
//				items.set("hasRecords", hasRecords);
//			}
//			record.set("list", daliyItems);
//		}
//		return Ret.create("list",list).set("daliyRecords" , daliyRecords);
    }
}
